﻿Class FLMonitor


Public Const __NUM_FUNC_EXP_DATOS__ As Integer = 5
Public Const __NUM_DATOS__ As Integer = 1


Private negocio As CServicioMonitorFL 
Private lstEstatusPS As List(Of String )
Private servicioGenerales As CSServiciosGenerales





Private MascaraActiva(__NUM_FUNC_EXP_DATOS__,__NUM_DATOS__) As Byte

Public Enum Activador
  Activado = 1
  DesActivado = 0
End Enum

Public Enum FuncExp
  BSO = 0
  PS  = 1
  PEJ = 2
  PAJ = 3   
  Distrib = 4
  DistribFondoImporte = 5
End Enum




Public Sub new()

    
    InitializeComponent()
    
    negocio = New CServicioMonitorFL ()
    servicioGenerales = New CSServiciosGenerales()
    lstEstatusPS = negocio.ObtenerDiscribEstatusPS () 
    
    MascaraActiva(FuncExp.BSO,0)                  = 1 'BSO
    MascaraActiva(FuncExp.PS ,0)                  = 2 'PS
    MascaraActiva(FuncExp.PEJ,0)                  = 3 'PEJ
    MascaraActiva(FuncExp.PAJ,0)                  = 4 'PAJ
    MascaraActiva(FuncExp.Distrib ,0)             = 4  'Distrib Info Gral
    MascaraActiva(FuncExp.DistribFondoImporte ,0) = 5   'Distrib Fondo-Importe

    MascaraActiva(FuncExp.BSO,1)                  = Activador.DesActivado  
    MascaraActiva(FuncExp.PS ,1)                  = Activador.DesActivado  
    MascaraActiva(FuncExp.PEJ,1)                  = Activador.DesActivado  
    MascaraActiva(FuncExp.PAJ,1)                  = Activador.DesActivado  
    MascaraActiva(FuncExp.Distrib ,1)             = Activador.DesActivado  
    MascaraActiva(FuncExp.DistribFondoImporte ,1) = Activador.DesActivado  

    dtFecIniExp.SelectedDate = Now  
    dtFecFinExp.SelectedDate = Now
    MostrarBotonReenvio()
    Mouse.OverrideCursor = Nothing

End Sub



#Region "Monitor en Línea"


    Private Sub dtFecIni_SelectedDateChanged(ByVal sender As System.Object , ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles dtFecIni.SelectedDateChanged

  Dim dpicker = CType (sender,DatePicker)
  Dim sMsgError As String = ""
  dim lstBSOMonitor As List(Of CTMonitorBSO )




  lstBSOMonitor = negocio.CargarBSOMonitor (dpicker.SelectedDate,sMsgError)
  If lstBSOMonitor is Nothing then 
     MessageBox.Show("No se pudo cargar la información: " & sMsgError, "Monitor de Flujo de Liquidez", MessageBoxButton.OK,MessageBoxImage.Exclamation)
     Exit Sub 
  End If

  grdMonitorBSO.ItemsSource = lstBSOMonitor
  grdMonitorBSO.UpdateLayout()

  txtNumPSMonitor.Text = ""
  txtNumPEJMonitor.Text = ""
  txtDetalleNumDistrib.Text = ""
  txtDetalleNumPAJ.Text = ""



End Sub
    
    Private Sub grdMonitorBSO_SelectionChanged(ByVal sender As System.Object , ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdMonitorBSO.SelectionChanged
  Dim bsoSeleccionada = CType(grdMonitorBSO.SelectedItem, CTMonitorBSO ) 'BSO Seleccionado
  Dim lstPSMonitor  As List(Of CTMonitorPS )  

   If bsoSeleccionada is Nothing then    
       grdMonitorPS.ItemsSource = New List(Of CTMonitorPS )              
      'e.Handled = True 
      Exit Sub
   End If



  lstPSMonitor = negocio.ObtenerPSMonitorXBSO(bsoSeleccionada.BSOId )  

  grdMonitorPS.ItemsSource  = lstPSMonitor
  grdMonitorPS.UpdateLayout()

  txtNumPSMonitor.Text = lstPSMonitor.Count 
  txtNumPEJMonitor.Text = ""
  txtDetalleNumDistrib.Text = ""
  txtDetalleNumPAJ.Text = ""

End Sub
    
    Private Sub grdMonitorPS_SelectionChanged(ByVal sender As System.Object , ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdMonitorPS.SelectionChanged
Dim psSeleccionada = CType(grdMonitorPS.SelectedItem, CTMonitorPS  ) 'PS Seleccionado
Dim lstPEJMonitor  As List(Of CTMonitorPEJ )



If psSeleccionada is Nothing then 
      grdMonitorPEJ.ItemsSource = New List(Of CTMonitorPEJ )      
     ' e.Handled = True 
      Exit Sub
 End If


 lstPEJMonitor =   negocio.ObtenerPEJMonitorXPS (psSeleccionada.IdPS)


 grdMonitorPEJ.ItemsSource = lstPEJMonitor  
 grdMonitorPEJ.UpdateLayout()

 txtNumPEJMonitor.Text =  lstPEJMonitor.Count () 
  txtDetalleNumDistrib.Text = ""
  txtDetalleNumPAJ.Text = ""

End Sub
    
    Private Sub grdMonitorPEJ_SelectionChanged(ByVal sender As System.Object , ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdMonitorPEJ.SelectionChanged

 Dim pejSeleccionada = CType(grdMonitorPEJ.SelectedItem, CTMonitorPEJ   ) 'Pej Seleccionado
 Dim lstDistribGralMonitor  As List(Of CTDistribucionGL)
 Dim lstPAJMonitor          As List(Of CTMonitorPAJ )



If pejSeleccionada is Nothing then   
      grdMonitorGralDistrib.ItemsSource =   New List(Of CTDistribucionGL)  
       grdMonitorPAJ.ItemsSource = New List(Of CTMonitorPAJ )

      'e.Handled = True 
      Exit Sub
 End If

 lstDistribGralMonitor =   negocio.ObtenerDistribGralXPEJ (pejSeleccionada.IdPEJ )
 lstPAJMonitor         =   negocio.ObtenerPAJXPEJ (pejSeleccionada.IdPEJ)


 grdMonitorGralDistrib.ItemsSource =  lstDistribGralMonitor
 grdMonitorGralDistrib.UpdateLayout()


 grdMonitorPAJ.ItemsSource = lstPAJMonitor 
 grdMonitorPAJ.UpdateLayout ()

 

 txtDetalleNumDistrib.Text = lstDistribGralMonitor.Count
 txtDetalleNumPAJ.Text = lstPAJMonitor.Count 
 


End Sub
    
    Private Sub grdMonitorGralDistrib_SelectionChanged(ByVal sender As System.Object , ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles grdMonitorGralDistrib.SelectionChanged

Dim pdISSeleccionada = CType(grdMonitorGralDistrib.SelectedItem, CTDistribucionGL) 
Dim lstPEJMonitor  As List(Of CTMonitorDustribDetalleGL )

If pdISSeleccionada is Nothing then       
       grdMonitordetDistrib.ItemsSource = New List(Of CTMonitorDustribDetalleGL )
      'e.Handled = True 
      Exit Sub
 End If


 lstPEJMonitor =   negocio.ObtenerDistribDetXPEJDB (pdISSeleccionada.PartidaEJ,pdISSeleccionada.SecDistrib)


 grdMonitordetDistrib.ItemsSource = lstPEJMonitor  
 grdMonitordetDistrib.UpdateLayout()

 
End Sub


#End Region


#Region "Exportación de Información"

    Private Sub chkReporte_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles chkReporte.Checked
        dtFecIniExp.SelectedDate = Date.Now
        dtFecFinExp.SelectedDate = dtFecIniExp.SelectedDate
        dtFecIniExp.IsEnabled = True
        dtFecFinExp.IsEnabled = False
        chkBSO.IsEnabled = False
        chkBSO.IsChecked = False
        chkPS.IsEnabled = False
        chkPS.IsChecked = False
        MascaraActiva(FuncExp.BSO, 1) = Activador.Activado
    End Sub

    Private Sub chkReporte_Unchecked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles chkReporte.Unchecked
        dtFecIniExp.IsEnabled = True
        dtFecFinExp.IsEnabled = True
        chkBSO.IsEnabled = True
        chkBSO.IsChecked = False
        chkPS.IsEnabled = False
        chkPS.IsChecked = False
        MascaraActiva(FuncExp.BSO, 1) = Activador.DesActivado
    End Sub

    Private Sub dtFecIniExp_SelectedDateChanged(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles dtFecIniExp.SelectedDateChanged
        If chkReporte.IsChecked Then
            Me.dtFecFinExp.SelectedDate = Me.dtFecIniExp.SelectedDate
            Me.dtFecFinExp.IsEnabled = False
        End If
    End Sub

    Private Sub chkBSO_Checked(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles chkBSO.Checked
        chkPS.IsEnabled = True
        chkPS.IsChecked = False
        MascaraActiva(FuncExp.BSO, 1) = Activador.Activado
    End Sub

  Private Sub chkBSO_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkBSO.Unchecked
     chkPS.IsEnabled = false
     chkPS.IsChecked = false 
     MascaraActiva(FuncExp.BSO,1) = Activador.DesActivado                   
  End Sub    

  Private Sub chkPS_Checked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkPS.Checked
     chkPEJ.IsEnabled = True
     chkPEJ.IsChecked = false 
     MascaraActiva(FuncExp.PS,1) = Activador.Activado 
  End Sub
  
  Private Sub chkPS_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkPS.Unchecked
     chkPEJ.IsEnabled = false
     chkPEJ.IsChecked = false 
     MascaraActiva(FuncExp.PS,1) = Activador.DesActivado  
  End Sub

  Private Sub chkPEJ_Checked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkPEJ.Checked
     chkPAJ.IsEnabled = True
     chkPAJ.IsChecked = false 
     MascaraActiva(FuncExp.PEJ,1) = Activador.Activado  
  End Sub

  Private Sub chkPEJ_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkPEJ.Unchecked
     chkPAJ.IsEnabled = False
     chkPAJ.IsChecked = false 
     MascaraActiva(FuncExp.PEJ ,1) = Activador.DesActivado  
  End Sub
  
  Private Sub chkPAJ_Checked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkPAJ.Checked

     chkDistrib.IsEnabled = True
     chkDistrib.IsChecked = false 
     MascaraActiva(FuncExp.PAJ,1) = Activador.Activado  

  End Sub
  
  Private Sub chkPAJ_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkPAJ.Unchecked
      chkDistrib.IsEnabled = false
      chkDistrib.IsChecked = false 
      MascaraActiva(FuncExp.PAJ,1) = Activador.DesActivado  
  End Sub

  Private Sub chkDistrib_Checked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkDistrib.Checked
      chkDistribFondo.IsEnabled = True
      chkDistribFondo.IsChecked = false 
      MascaraActiva(FuncExp.Distrib,1) = Activador.Activado  
  End Sub

  Private Sub chkDistrib_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkDistrib.Unchecked
      chkDistribFondo.IsEnabled = False
      chkDistribFondo.IsChecked = false 
      MascaraActiva(FuncExp.Distrib,1) = Activador.DesActivado  
  End Sub

  Private Sub chkDistribFondo_Checked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkDistribFondo.Checked
     MascaraActiva(FuncExp.DistribFondoImporte,1) = Activador.Activado  
  End Sub

  Private Sub chkDistribFondo_Unchecked(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles chkDistribFondo.Unchecked
     MascaraActiva(FuncExp.DistribFondoImporte ,1) = Activador.DesActivado       
  End Sub



  Private Sub btnExportarExcel_Click(ByVal sender As System.Object , ByVal e As System.Windows.RoutedEventArgs) Handles btnExportarExcel.Click
      
      Dim resultadoDialog As Boolean
      Dim sRutaArchivo    As String  = ""
      Dim dialog = new Microsoft.Win32.SaveFileDialog ()
      Dim sMsgError  As String = ""



     '1) Validar periodo 
      
        if dtFecFinExp.SelectedDate < dtFecIniExp.SelectedDate  then 
           MessageBox.Show("La fecha final debe ser mayor o igual que la fecha de inicial", "Exportación de información", MessageBoxButton.OK,MessageBoxImage.Exclamation)
           Exit Sub 
        End If
      
        
      '2)Validar quem al menos una opción este activada

        If MascaraActiva(0,1) = Activador.DesActivado then 
           MessageBox.Show("No ha seleccionado una opción.", "Exportación de información", MessageBoxButton.OK,MessageBoxImage.Exclamation)
           Exit Sub 
        End If
        
       '3) Obtener la ruta y nombre del archivo a generar

        dialog.FileName = ""
        dialog.DefaultExt= "xls"
        dialog.Filter = "Excel documents|*.xls;*.xlsx"

        resultadoDialog = dialog.ShowDialog()
        
        If resultadoDialog = True then 
          sRutaArchivo = dialog.FileName
        Else 
           MessageBox.Show("No se pudo obtener la ruta del archivo","Carga de comisiones",MessageBoxButton.OK,MessageBoxImage.Exclamation)
           Exit sub
        End If

        Mouse.OverrideCursor = Cursors.Wait
        Dim reporteGenerado As Boolean
        If chkReporte.IsChecked Then
            reporteGenerado = negocio.ExportarReporteLiqExcel("FONDOS", dtFecIniExp.SelectedDate, sRutaArchivo, sMsgError)
            If reporteGenerado Then
                reporteGenerado = negocio.ExportarReporteLiqExcel("PORVENIR", dtFecIniExp.SelectedDate, sRutaArchivo, sMsgError)
            End If
        Else
            reporteGenerado = negocio.ExportarInfoAExcel(dtFecIniExp.SelectedDate, dtFecFinExp.SelectedDate, sRutaArchivo, MascaraActiva, sMsgError)
        End If
        If reporteGenerado = False Then
            MessageBox.Show("No se pudo generar la información correctamente, debido a:" & sMsgError, "Exportación de Información a Excel", MessageBoxButton.OK, MessageBoxImage.Error)
        Else
            MessageBox.Show("La información ha sido exportada correctamente.", "Exportación de Información a Excel", MessageBoxButton.OK, MessageBoxImage.Information)
        End If


        


      Mouse.OverrideCursor = Nothing  


  End Sub  






#End Region

#Region "Reenvio de Distribución a Decalog"
    Private Sub MostrarBotonReenvio()
        Dim idUsuario As String = CServiciosMacrosSyBaseDB.IDUSUARIO.ToString()
        Dim catalogo = New CTCatalogoGenerico()
        Dim lstCatalogo As List(Of CTCatalogoGenerico) = catalogo.ObtieneCatalogo(14)
        If lstCatalogo.FindAll(Function(x) x.Valor = idUsuario).Count > 0 Then
            btnReenvioDecalog.Visibility = Windows.Visibility.Visible
        End If
        
        
    End Sub

    Private Sub btnReenvioDecalog_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnReenvioDecalog.Click
        Mouse.OverrideCursor = Cursors.Wait
        If ValidarSeleccion Then
            If MessageBox.Show ("¿Desea reactivar distribución para reenvío a decalog?", "Monitor FL", MessageBoxButton.YesNo, MessageBoxImage.Question)  = MessageBoxResult.Yes Then
                Dim eventoBit = CBitacoraFRIDA.GenerarEvento(CBitacoraFRIDA.CveEventosBit.REACTIVAR_DISTRIBUCION, CServiciosMacrosSyBaseDB.IDUSUARIO, "FLMonitor.xaml -> btnReenvioDecalog")
                
                Try
                    Dim solicitud As CTMonitorPS = grdMonitorPS.SelectedItem
                    Dim distribucion As CTDistribucionGL = grdMonitorGralDistrib.SelectedItem
                    eventoBit.GuadarDetalle("idPS", solicitud.IdPS)
                    eventoBit.GuadarDetalle("idPEJ", distribucion.PartidaEJ)
                    eventoBit.GuadarDetalle("Sec", distribucion.SecDistrib)
                    eventoBit.GuadarDetalle("FolioOrden", distribucion.FolioOrden)
                    eventoBit.GuadarDetalle("Observacion", distribucion.Observacion)
                    negocio.ReactivarDistribucion(solicitud.IdPS, distribucion.PartidaEJ, distribucion.SecDistrib)
                    Dim lista = grdMonitorGralDistrib.ItemsSource
                    For Each dist As CTDistribucionGL In lista
                        If dist.PartidaEJ = distribucion.PartidaEJ And dist.SecDistrib = distribucion.SecDistrib Then
                            dist.FolioOrden = ""
                            dist.EnviadoADecalog = False
                            dist.Observacion = ""
                            dist.NombreArchivo = ""
                            dist.EstatusRecupFolDec = CTDistribucionGL.enumEstatusFolioRecupDecalog.NO_RECUPERADO
                        End If
                    Next
                    grdMonitorGralDistrib.ItemsSource = lista
                    grdMonitorGralDistrib.Items.Refresh
                    servicioGenerales.RegistrarNotificacion("Monitor FL - Se reactiva distribución")
                    eventoBit.ActualizarFechaFinDelEvento()
                    MessageBox.Show("Operación Exitosa" , "Monitor FL", MessageBoxButton.OK, MessageBoxImage.Information)
                    
                Catch ex As Exception
                    Dim errorBit = eventoBit.GuardarError("Error al reactivar distribución: " & ex.Message)
                    eventoBit.ActualizarFechaFinDelEvento()
                    MessageBox.Show("Error TI500. Error al reactivar distribución: " & ex.Message & " -Codigo:" & errorBit.IdError, "Monitor FL", MessageBoxButton.OK, MessageBoxImage.Error)
                    Mouse.OverrideCursor = Nothing
                End Try
                
                
            End If
            
        End If
        Mouse.OverrideCursor = Nothing

    End Sub

    Private Function ValidarSeleccion() As Boolean
        
        If grdMonitorGralDistrib.SelectedItem Is Nothing Then
            MessageBox.Show ("Se debe seleccionar una distribución.", "Monitor FL", MessageBoxButton.OK, MessageBoxImage.Exclamation) 
            Return False
        End If

        Dim bso As CTMonitorBSO = grdMonitorBSO.SelectedItem
        If Not bso.Estatus.Equals("ABIERTA") Then
            MessageBox.Show ("Se debe seleccionar una Boleta de Solicitud de Operaciones con wstatus ABIERTA.", "Monitor FL", MessageBoxButton.OK, MessageBoxImage.Exclamation) 
            Return False
        End If

        Dim distribucion As CTDistribucionGL = grdMonitorGralDistrib.SelectedItem
        If Not distribucion.EnviadoADecalog Then
            MessageBox.Show ("Se debe seleccionar una distribución enviada a Decalog.", "Monitor FL", MessageBoxButton.OK, MessageBoxImage.Exclamation) 
            Return False
        End If
        'If distribucion.EstatusRecupFolDec = CTDistribucionGL.enumEstatusFolioRecupDecalog.NO_RECUPERADO Then
        '    MessageBox.Show ("Se debe recuperar la respuesta de TLOADER de la distribución en:" & vbCrLf & "Distribución de liquidez -> Recuperación de Folios Decalog", "Monitor FL", MessageBoxButton.OK, MessageBoxImage.Exclamation) 
        '    Return False
        'End If

        Return True
    End Function
#End Region


End Class


Public Class CColorearEstatusPS
    Implements IValueConverter


    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If not value.Equals ("")   Then                    
           Dim valor As String    =  value.ToString ()

           
           Select Case valor 

              Case "CANCELADA"
                     Return Brushes.red

              Case "CERRADA_INCOMPLETA"
                   Return Brushes.Orange 

              Case else

                  Return Brushes.LimeGreen 

           End Select


            
        Else
            Return Brushes.Transparent 
        End If

         
          
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New Exception
    End Function



End Class
